﻿// Decompiled with JetBrains decompiler
// Type: HttpHelper
// Assembly: MT5Trade, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 8045A2CB-DBD6-41AD-8804-F98CAC1BDC8D
// Assembly location: C:\projects\trade\trade_tool\trade0812\MT5Trade.dll

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

#nullable enable
public class HttpHelper
{
  private static readonly HttpClient httpClient = new HttpClient();

  static HttpHelper()
  {
    httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; Maxthon 2.0)");
  }
  public static string Get(string urlString)
  {
    try
    {
      Task<string> task = httpClient.GetStringAsync(urlString);
      task.Wait();
      return task.Result;
    }
    catch (HttpRequestException ex)
    {
      throw new Exception("接受服务器返回页面时发生错误！", ex);
    }
    catch (TaskCanceledException ex)
    {
      throw new Exception("请求超时！", ex);
    }
    catch (Exception ex)
    {
      throw new Exception("读取页面数据时发生错误！", ex);
    }
  }

  public static string Post(string url, string param)
  {
    try
    {
      var content = new StringContent(param, Encoding.UTF8, "application/json");
      Task<HttpResponseMessage> task = httpClient.PostAsync(url, content);
      task.Wait();
      Task<string> readTask = task.Result.Content.ReadAsStringAsync();
      readTask.Wait();
      return readTask.Result;
    }
    catch (Exception ex)
    {
      throw new Exception("发送POST请求时发生错误！", ex);
    }
  }

  public static string NewPost(string url, string param)
  {
    try
    {
      var content = new StringContent(param, Encoding.UTF8, "application/json");
      Task<HttpResponseMessage> task = httpClient.PostAsync(url, content);
      task.Wait();
      
      // Handle both success and error responses
      Task<string> readTask = task.Result.Content.ReadAsStringAsync();
      readTask.Wait();
      return readTask.Result;
    }
    catch (HttpRequestException ex)
    {
      Console.Write("连接服务器失败!");
      // Return empty string on connection failure to match original behavior
      return string.Empty;
    }
    catch (Exception ex)
    {
      throw new Exception("发送POST请求时发生错误！", ex);
    }
  }
}
